package controllers

import (
	"db2_ddl_search/db2"
	"db2_ddl_search/service"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gohouse/gorose/v2"
)

func GetTreeChild(context *gin.Context) {

	//父节点
	parentId := context.PostForm("parentId")
	//节点类型
	nodetype := context.PostForm("type")

	//模式
	scema := context.PostForm("scema")

	//根节点
	if parentId == "0" {
		list, err := db2.GetSchemaList()

		if err == nil && list != nil && len(list) > 0 {
			context.JSON(http.StatusOK, list)

			return
		}
	} else if nodetype == "SCEMA" {

		nodes := make([]gorose.Data, 0)

		node := make(gorose.Data)
		node["id"] = parentId + "_TABLES"
		node["NAME"] = "Tables"
		node["TYPE"] = "Tables"
		node["SCEMA"] = scema

		nodes = append(nodes, node)

		node = make(gorose.Data)
		node["id"] = parentId + "_VIEWS"
		node["NAME"] = "Views"
		node["TYPE"] = "Views"
		node["SCEMA"] = scema

		nodes = append(nodes, node)

		node = make(gorose.Data)
		node["id"] = parentId + "_FUNCTIONS"
		node["NAME"] = "Functions"
		node["TYPE"] = "Functions"
		node["SCEMA"] = scema

		nodes = append(nodes, node)

		node = make(gorose.Data)
		node["id"] = parentId + "_PROCEDURES"
		node["NAME"] = "Procedures"
		node["TYPE"] = "Procedures"
		node["SCEMA"] = scema

		nodes = append(nodes, node)

		node = make(gorose.Data)
		node["id"] = parentId + "_TRIGGERS"
		node["NAME"] = "Triggers"
		node["TYPE"] = "Triggers"
		node["SCEMA"] = scema

		nodes = append(nodes, node)

		context.JSON(http.StatusOK, nodes)

		return
	} else if nodetype == "Triggers" || nodetype == "Procedures" || nodetype == "Views" || nodetype == "Functions" || nodetype == "Tables" || nodetype == "Views" {
		childtype := strings.ToUpper(nodetype[0:(len(nodetype) - 1)])

		list, err := service.GetObjectsBySchemeAndType(scema, childtype)

		if err == nil && list != nil && len(list) > 0 {
			context.JSON(http.StatusOK, list)

			return
		}
	}
	emlist := make([]gorose.Data, 0)
	context.JSON(http.StatusOK, emlist)
	return

}
